package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicListContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.UsedAdapter
import fm.dongman.animefm.view.listener.LoadMoreRecyclerOnScrollListener
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ComicModel
import fm.dongman.presenterlib.presenter.ComicListPresenter
import kotlinx.android.synthetic.main.fragment_comic_list.*
import kotlinx.android.synthetic.main.item_comic_list.view.*
import org.jetbrains.anko.onClick

/**
 * 动漫列表
 * Created by shize on 2017/11/5.
 */
class ComicListFragment : BaseFragment(), ComicListContract.IComicListView {
    private var mPresenter: ComicListContract.IComicListPresenter? = null // 数据控制器
    private var mType: String = TYPE_SEARCH // 列表类型
    private var mKey: String? = null // 关键字 or ID

    private lateinit var mScrollListener: LoadMoreRecyclerOnScrollListener // 滑动监听器

    private lateinit var mComicAdapter: ComicListAdapter // 动漫列表适配器
    private val mComicList: ArrayList<IModel.IComicModel> = ArrayList() // 动漫数据集合

    private lateinit var mFooterView: View // 列表底部 View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val view = inflater!!.inflate(R.layout.fragment_comic_list, container, false)
        ComicListPresenter(this, Injection.provideComicListRepository())
        return view
    }

    override fun setNewParam(key: String) {
        mKey = key
        requestListData(1)
    }

    override fun requestListData(page: Int) {
        mPresenter?.setKey(mType, mKey, page)
        mComicAdapter.addFooterView(mFooterView)
        mScrollListener.clearPage()
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun initData() {
        if (arguments != null) {
            mType = arguments.getString(FLAG_TYPE)
            if (mKey == null)
                mKey = arguments.getString(FLAG_ID)
        }
    }

    override fun bindData() {
        bindToolbar()
        bindComicList()
    }

    /**
     * 绑定 Toolbar
     */
    private fun bindToolbar() {
        when (mType) {
            TYPE_LOOK -> {
                if (mKey != null) {
                    mComicListToolbar.visibility = View.GONE
                    return
                }
                mComicListToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
                mComicListToolbar.setNavigationOnClickListener {
                    ActivityHelper.backActivity(activity)
                }
            }
            TYPE_SEARCH -> {
                mComicListToolbar.visibility = View.GONE
            }
        }
    }

    /**
     * 绑定列表
     */
    @SuppressLint("InflateParams")
    private fun bindComicList() {
        mFooterView = LayoutInflater.from(activity).inflate(R.layout.layout_loading, null)
        mComicAdapter = ComicListAdapter(activity, mComicList)
        mComicAdapter.addFooterView(LayoutInflater.from(activity).inflate(R.layout.layout_loading, null))
        mComicListRecycler.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        mComicListRecycler.adapter = mComicAdapter
        mScrollListener = object : LoadMoreRecyclerOnScrollListener(mComicListRecycler.layoutManager) {
            override fun onLoadMore(currentPage: Int) {
                mPresenter?.setKey(mType, mKey, currentPage)
            }
        }
        mComicListRecycler.addOnScrollListener(mScrollListener)
        if (mType == TYPE_SEARCH)
            requestListData(1)
    }

    override fun setPresenter(presenter: ComicListContract.IComicListPresenter) {
        mPresenter = presenter
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError("动漫列表加载失败！")
        onStateChanged(MultiStateLayout.EMPTY)
    }

    override fun showComicList(comics: List<IModel.IComicModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mComicList.clear()
        mComicList.addAll(comics)
        mComicAdapter.notifyDataSetChanged()
        if (comics.size < 10) {
            // 加载完毕
            mComicAdapter.removeFooterView()
        }
    }

    override fun showMoreComicList(comics: List<IModel.IComicModel>) {
        if (comics.isEmpty()) {
            // 加载完毕
            mComicAdapter.removeFooterView()
            return
        }
        mComicList.addAll(comics)
        mComicAdapter.notifyDataSetChanged()
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    /**
     * 状态改变
     * @param state 状态
     */
    private fun onStateChanged(state: Int) {
        mComicListMultiState?.changeState(state)
    }

    companion object {
        private val FLAG_TYPE = "fm.dongman.animefm.comicList.flagType" // 类型 key
        private val FLAG_ID = "fm.dongman.animefm.comicList.flagId" // id key

        val TYPE_SEARCH = ComicListContract.IComicListPresenter.TYPE_SEARCH // 搜索
        val TYPE_LOOK = ComicListContract.IComicListPresenter.TYPE_LOOK // 观看记录

        /**
         * 获取实例
         */
        fun getInstance(flagType: String, flagId: String?): ComicListFragment {
            val bundle = Bundle()
            bundle.putString(FLAG_TYPE, flagType)
            bundle.putString(FLAG_ID, flagId)
            val fragment = ComicListFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    /**
     * 列表适配器
     */
    private class ComicListAdapter constructor(private val mContext: Context, private val mData: List<IModel.IComicModel>)
        : UsedAdapter<ComicListAdapter.ComicListViewHolder>() {
        @SuppressLint("InflateParams")
        override fun onCreateVH(): ComicListViewHolder =
                ComicListViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_comic_list, null))

        @SuppressLint("SetTextI18n")
        override fun onBindVH(holder: ComicListViewHolder, position: Int) {
            val model: ComicModel = mData[position] as ComicModel
            Glide.with(mContext).load(model.imgUrl).bitmapTransform(CenterCrop(mContext), GlideRoundTransform(mContext, 2)).into(holder.mCover)
            holder.mTitle.text = model.title + "(" + model.year + ")"
            holder.mSubtitle.text = "更新至" + model.episodes + "集"
            holder.mThirdTitle.text = model.genre
            holder.mInfoLeft.text = model.country
            holder.mInfoRight.text = model.rateScore
            holder.itemView.onClick {
                val intent = Intent(mContext, SingleActivity::class.java)
                intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ANIME_INFO)
                intent.putExtra(SingleActivity.BUNDLE_EXTRA_KEY_ID, model.id)
                ActivityHelper.startActivity(mContext as Activity, intent)
            }
        }

        override fun getDataTotal(): Int = mData.size

        private class ComicListViewHolder(itemView: View) : UsedViewHolder(itemView) {
            val mCover: ImageView = itemView.mIvComicListCover
            val mTitle: TextView = itemView.mTvComicListTitle
            val mSubtitle: TextView = itemView.mTvComicListSubTitle
            val mThirdTitle: TextView = itemView.mTvComicListThirdTitle
            val mInfoLeft: TextView = itemView.mTvComicListLastWatchEpisode
            val mInfoRight: TextView = itemView.mTvComicListWatchTime
        }
    }
}